<template>
  <div>
    <MBX Biao="商品管理" Biao1="商品列表"></MBX>

    <!-- 卡片 -->
    <el-card class="mt">
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- 步骤条 -->
      <el-steps class="mt" :active="activeName * 1" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addForm" :rules="rules" ref="addForm">
        <!-- Tab栏 -->
        <el-tabs
          class="mt"
          v-model="activeName"
          @tab-click="handleClick"
          :before-leave="beforeLeave"
          tab-position="left"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类">
              <span>选中的商品分类：</span>
              <el-cascader
                v-model="checkedArr"
                :options="goodsData"
                :props="addProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 动态参数 -->
            <el-form-item
              :label="item1.attr_name"
              v-for="item1 in dongTai"
              :key="item1.attr_id"
            >
              <el-checkbox-group v-model="item1.attr_vals">
                <el-checkbox
                  :label="item2"
                  v-for="(item2, index) in item1.attr_vals"
                  :key="item2.attr_id"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in jinTai"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://www.ysqorz.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :headers='headers'
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
             <!-- 富文本编辑器 -->
             <quill-editor v-model="addForm.goods_introduce" />
             <el-button type="primary" class="mt" @click='addGoodsSP'>添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

    </el-card>
    <!--  -->
  </div>
</template>

<script>
import { getCatel, getCshu ,getShangPing} from "@/http/api";
import _ from 'lodash';
export default {
  data() {
    return {
      //配置上传的请求头信息
      headers:{
        Authorization:sessionStorage.getItem('token')
      },
      activeName: "0",
      tabPosition: "left",
      checkedArr: [], //已选中的商品分类数组
      goodsData: [], //商品分类数据
      addProps: {
        //商品分类配置项
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      addForm: {
        goods_name: "",
        goods_cat: "",
        goods_price: "0",
        goods_number: '0',
        goods_weight: "0",
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      jinTai: [], //获取静态参数数组
      dongTai: [], //获取静态参数数组
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          // { required: 'date', required: true, message: '请输入商品价格', trigger: 'change' }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
          // { required: 'date', required: true, message: '请输入商品重量', trigger: 'change' }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
          // { required: 'date', required: true, message: '请输入商品数量', trigger: 'change' }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  computed: {
    //利用计算属性获取最后一个id
    currId() {
      return this.checkedArr[this.checkedArr.length - 1];
    },
  },
  methods: {
    //确定向后台添加商品信息
    async addGoodsSP(){
       //1；处理分类数组，转换为以逗号分隔的字符串
        this.addForm.goods_cat=this.checkedArr.join(',')
       //2:将动态参数和静态属性合并，赋值给attrs
       //第一步：处理动态参数  使用lodash中的cloneDeep实现深拷贝，解决对象之间互相印象的问题
       let dongPrams=_.cloneDeep(this.dongTai)
       console.log('动态参数处理',dongPrams);
       dongPrams=dongPrams.map(item=>{
         return {
           'attr_id':item.attr_id, 
           'attr_vals':item.attr_vals.join(',')
         }
       })
       console.log('动态参数处理',dongPrams);
       
       //第二部：处理静态参数
       let jinPrams=_.cloneDeep(this.jinTai)
       jinPrams=jinPrams.map(item=>{
         return {
           'attr_id':item.attr_id, 
           'attr_vals':item.attr_vals
         }
       })
       //第三步:合并动态参数和静态属性 合并处理后的数据
       let metagParams=[...dongPrams,...jinPrams]
       //第四步：将合并后的动静参数赋值给attrs
       this.addForm.attrs=metagParams
       //第五步：调用接口传递给后台
       this.addForm=_.cloneDeep(this.addForm)
       await getShangPing(this.addForm)
       //添转到商品列表页面
       this.$router.push('/goods')

    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(){},
    //删除图片时回调
    handleRemove(file){
      console.log('删除上传图片时的回调',file);
      //通过findIndex方法找出要删除的元素在上传成功的数组中的下标，本地删除
      //tmp_path  log后台数据体现
      const tem_path=file.response.data.tmp_path
      //通过findIndex方法找出要删除的元素在上传成功数组中的下标
      const index=this.addForm.pics.findIndex(item=>{
        return item.pic===tem_path
      })
      //删除数组中的图片这个元素
      this.addForm.pics.splice(index,1)
    },
    //成功上传时的回调
    handleSuccess(res){
      console.log('上传图片成功时的回调',res);
      //生成图片上传的对象
      let picObj={pic:res.data.tmp_path}
      //再添加到pics数组
      this.addForm.pics.push(picObj)
      // console.log('要上传的数组',this.addForm.pics);
    },
    //监听tab切换之前
    beforeLeave(newActive, oldActive) {
      console.log("newActive", newActive);
      console.log("oldActive:", oldActive);
      if (oldActive === "0" && this.checkedArr.length < 3) {
        this.$message({
          message: "您必须选择完三级分类后，才能进行下一步的选择",
          type: "error",
        });
        return false;
      }
    },
    //商品分类级联选择器改变时触发
    handleChange() {
      console.log("商品分类级联选择器改变时触发");
    },
    async handleClick() {
      console.log("我是第几个", this.activeName);
      if (this.activeName === "1") {
        //渲染动态参数  1是下标  tab栏的
        //调用接口将获取最后一个id的数组作为参数传递
        const res = await getCshu(this.currId);
        console.log("获取到的动态参数", res);
        //转为字符串转数组
        res.forEach((item) => {
          item.attr_vals = item.attr_vals.split(",");
        });
        this.dongTai = res;
        // console.log('动态参数的数据数组',this.dongTai);
      } else if (this.activeName === "2") {
        //渲染静态参数  2也是下标 tab栏的
        const res = await getCshu(this.currId, "only");
        console.log("获取到的静态参数", res);
        this.jinTai = res;
        // console.log('获取的静态数据的数组',this.jinTai);
      }
    },
    async getList() {
      const res = await getCatel();
      console.log("商品分类", res);
      this.goodsData = res;
    },
  },
};
</script>

<style scoped>
::v-deep .el-form-item__label {
  width: 100%;
  text-align: left;
}
::v-deep .ql-container{
  height: 300px;
}
</style>
